<template>
  <Center>
    <form action class="login-container" @submit.prevent="handleSubmit">
      <div class="form-item">
        <div class="input">
          <label for="text">账号：</label>
          <input
            id="text"
            @input="validateEmpty('loginId','账号不能为空')"
            type="text"
            v-model="userInfo.loginId"
          />
        </div>
        <FormError :msg="error.loginId" />
      </div>
      <div class="form-item">
        <div class="input">
          <label for="pwd">密码：</label>
          <input
            id="pwd"
            v-model="userInfo.loginPwd"
            @input="validateEmpty('loginPwd','密码不能为空')"
            type="password"
            autocomplete="new-password"
          />
        </div>
        <FormError :msg="error.loginPwd" />
      </div>
      <div class="form-item">
        <div class="input">
          <label></label>
          <button>{{$store.state.loginUser.isLoading? "isLoading":"登录"}}</button>
        </div>
        <FormError :isCenter="true" />
      </div>
    </form>
  </Center>
</template>

<script>
import Center from "../components/Center";
import FormError from "../components/FormError";
export default {
  components: {
    Center,
    FormError,
  },
  data() {
    return {
      userInfo: {
        loginId: "",
        loginPwd: "",
      },
      error: {
        loginId: "",
        loginPwd: "",
      },
    };
  },
  methods: {
    //非空验证
    validateEmpty(field, msg) {
      if (this.userInfo[field]) {
        this.error[field] = "";
        return true;
      } else {
        this.error[field] = msg;
        return false;
      }
    },
    async handleSubmit() {
      if (this.$store.state.loginUser.isLoading) {
        //正在登录中
        return;
      }
      let validate1 = this.validateEmpty("loginId", "账号不能为空");
      let validate2 = this.validateEmpty("loginPwd", "密码不能为空");
      if (validate1 && validate2) {
        // 提交数据
        var result = await this.$store.dispatch(
          "loginUser/login",
          this.userInfo
        );
        if (result) {
          // 登录成功
          this.$router.push({ name: "Home" });
        } else {
          this.error.loginId = "账号/密码不正确";
        }
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  width: 400px;
}
.form-item .input {
  display: flex;
  outline: none;
}
.form-item label {
  width: 100px;
  display: inline-block;
  text-align: right;
  line-height: 41px;
}

.form-item input,
.form-item button {
  flex-grow: 1;
}
</style>